//
//  CalendarViewModel.swift
//  YOKO
//
//  Created by vivi on 16/5/30.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit

class CalendarViewModel: CalendarViewDelegate, CalendarViewDataSource {
    weak var viewController: ViewController?
    var calendarView: CalendarView
    
    init(viewController: ViewController?, calendarView: CalendarView) {
        self.viewController = viewController
        self.calendarView = calendarView
        
        self.calendarView.delegate = self
        self.calendarView.datasource = self
        
        //监听Notification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CalendarViewModel.updateAllCalendars_notificationHandler(_:)), name: YOKONotification.UPDATE_ALL_CALENDARS, object: nil) //监听所有的Calendar改变的UI
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CalendarViewModel.changeCurrentCalendar_notificationHandler(_:)), name: YOKONotification.CHANGE_CURRENT_CALENDAR, object: nil) //监听当前是否有CurrentCalendarId改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CalendarViewModel.updateCalendarId_notificationHandler(_:)), name: YOKONotification.UPDATE_CALENDAR_CAL_ID, object: nil) //监听是否有UserInfo改变
        
        calendarView.reloadAll()
    }
    
    //MARK: - CalendarView Delegate
    func calendarViewDidAddNewCalendar(calendarView: CalendarView, forName name: String) {
        // 添加一个日历本
        let api = ApiSync()
        let cal = Calendar()
        cal.summary = name
        cal.calendarId = String(NSDate().timeIntervalSince1970*1000)
        cal.isLocal = true
        
        try! uiRealm.write {
            uiRealm.add(cal)
        }
        calendarView.addCalendar(true)
        
        api.updateCalendarToServiceSync(cal, isAdd: true, callback: { (response, error) in
            let old_cal_id = cal.calendarId
            let cal_id = response!["data"]!["calendar_id"] as! String
            
            try! uiRealm.write {
                cal.calendarId = cal_id
                cal.etag = response!["data"]!["calendarEntry"]!!["etag"] as! String
            }
            
            let userInfo = [
                YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_OLD_CAL_ID: old_cal_id,
                YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_NEW_CAL_ID: cal_id
            ]
            NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_CALENDAR_CAL_ID, object: nil, userInfo: userInfo)
        })
    }
    
    func calendarViewDidTapCalendar(calendarView: CalendarView, atIndex index: Int, withUserInfo userInfo: AnyObject?) {
        
        //在这里实现仅仅抛出了Notification，之后的动作在监听CHANGE_CURRENT_CALENDAR的内部实现
        NSUserDefaults.setCurrentCalendarId(userInfo as! String)
        NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.CHANGE_CURRENT_CALENDAR, object: nil, userInfo: nil)
        viewController?.calendarViewState = 0 //收起来
    }
    
    func calendarViewDidChangeNameForCalendar(calendarView: CalendarView, toName name: String, atIndex index: Int, withUserInfo userInfo: AnyObject?) {
        guard let calendarInDB = uiRealm.objects(Calendar).filter("calendarId = %@", userInfo as! String).last else {
            fatalError("Cannot find the calendar to change name with calendarId of \(userInfo as! String)")
        }
                
        try! uiRealm.write {
            calendarInDB.summary = name
        }
        calendarView.reloadCalendarName(atIndex: index)
        
        if userInfo as! String == NSUserDefaults.getCurrentCalendarId() {
            //如果改名的是当前正在显示的Calendar,更新标题栏
            viewController?.navigationTitleView.title = name
        }
        
        ApiSync().updateCalendarToServiceSync(calendarInDB, isAdd: false) {
            response, error in
            //pass
        }
    }
    
    func calendarViewDidPressCalendarDeleteButton(calendarView: CalendarView, atIndex index: Int, withUserInfo userInfo: AnyObject?, isCurrentSelectedView: Bool) {
        guard let calendarInDB = uiRealm.objects(Calendar).filter("calendarId = %@", userInfo as! String).last else {
            fatalError("Cannot find the calendar to delete with calendarId of \(userInfo as! String)")
        }
        
        //在这里默认实现是删除Calendar的view,如果当前选择的日历被删除了，那么跳转到主日历本
        //calendarVC.deleteCalendar(view)
        if isCurrentSelectedView == true {
            let sys_cal = uiRealm.objects(Calendar).filter("category = %@ AND source = %@", CATEGORY_SYSTEM, SOURCE_MAIN).first
            NSUserDefaults.setCurrentCalendarId((sys_cal?.calendarId)!)
        }
        
        //更新数据库
        try! uiRealm.write {
            calendarInDB.deleted = true
        }
        
        //刷新UI
        calendarView.deleteCalendar(atIndex: index, animated: true)
        
        //上传，如果成功那么删除，如果没有成功的话，那么重新添加进去
        ApiSync().updateCalendarToServiceSync(calendarInDB, isAdd: false) {
            response, error in
            try! uiRealm.write {
                uiRealm.delete(calendarInDB)
            }
        }
    }
    
    //MARK: - CalendarView Datasource
    func calendarView_numberOfCalendars() -> Int {
        return uiRealm.objects(Calendar).filter("deleted = false").count
    }
    
    func calendarView_indexForSelectedCalendar() -> Int {
        for (i, singleCalendarView) in calendarView.calendarSelectorView.singleCalendarsViews.enumerate() {
            if singleCalendarView.userInfo as? String == NSUserDefaults.getCurrentCalendarId() {
                return i
            }
        }
        
        print("\(#function) --> Cannot find the current calendar id")
        return -1
    }
    
    func calendarView_nameForCalendarAtIndex(index: Int) -> String {
        return uiRealm.objects(Calendar).filter("deleted = false")[index].summary
    }
    
    func calendarView_userInfoForCalendarAtIndex(index: Int) -> AnyObject? {
        return uiRealm.objects(Calendar).filter("deleted = false")[index].calendarId
    }
    
    //MARK: - NotificationHandler
    
    @objc func updateAllCalendars_notificationHandler(notification: NSNotification) {
        calendarView.reloadAll()
    }
    
    @objc func changeCurrentCalendar_notificationHandler(notification: NSNotification) {
        calendarView.changeSelectedCalendar()
        viewController?.navigationTitleView.title = Config.getCurrentCalendar().summary
    }
    
    @objc func updateCalendarId_notificationHandler(notification: NSNotification) {
        let oldCalId = notification.userInfo![YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_OLD_CAL_ID] as! String
        
        for (i, singleCalendarView) in calendarView.calendarSelectorView.singleCalendarsViews.enumerate() {
            if singleCalendarView.userInfo as! String == oldCalId {
                calendarView.reloadCalendarUserInfo(atIndex: i)
                return
            }
        }
    }
}